package com.example.shiyan02

import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.shiyan02.controller.ProgramController
import com.example.shiyan02.model.ProgramModel
import com.example.shiyan02.view.ProgramView

class MainActivity : AppCompatActivity() {

    private lateinit var containerLayout: LinearLayout
    private lateinit var addButton: Button
    private lateinit var adviceButton: Button
    private lateinit var programInput: android.widget.EditText
    private lateinit var adviceResult: TextView

    private lateinit var programController: ProgramController
    private var textViewCounter = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        supportActionBar?.title = getString(R.string.app_name)

        initViews()
        setupMVC()
        setupEventListeners()
    }

    private fun initViews() {
        containerLayout = findViewById(R.id.containerLayout)
        addButton = findViewById(R.id.addButton)
        adviceButton = findViewById(R.id.adviceButton)
        programInput = findViewById(R.id.programInput)
        adviceResult = findViewById(R.id.adviceResult)
    }

    private fun setupMVC() {
        val model = ProgramModel()
        val view = ProgramView(programInput, adviceResult)
        programController = ProgramController(model, view, this)
    }

    private fun setupEventListeners() {

        addButton.setOnClickListener {
            addDynamicTextView()
        }


        adviceButton.setOnClickListener {
            programController.getProgramAdvice()
        }
    }

    private fun addDynamicTextView() {
        val newTextView = TextView(this).apply {
            text = "${getString(R.string.dynamic_text_prefix)} $textViewCounter"
            textSize = 16f
            setPadding(16, 8, 16, 8)
            setBackgroundColor(0xFFE3F2FD.toInt())
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(0, 4, 0, 4)
            }
        }

        containerLayout.addView(newTextView)
        textViewCounter++
    }
}